﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Minestorm.Evolved.GameLogic
{
    public static class BoundingHelper
    {
        public static float GetSphereRadius(Model model)
        {
            var modelCenter = Vector3.Zero; 
            float modelRadius;

            var boneTransforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(boneTransforms);

            foreach (ModelMesh mesh in model.Meshes)   
            {
                var meshBounds = mesh.BoundingSphere;
                var transform = boneTransforms[mesh.ParentBone.Index];
                var meshCenter = Vector3.Transform(meshBounds.Center, transform);   
  
                modelCenter += meshCenter;   
            }   
  
            modelCenter /= model.Meshes.Count;   
  
            modelRadius = 0;   
  
            foreach (ModelMesh mesh in model.Meshes)   
            {   
                var meshBounds = mesh.BoundingSphere;
                var transform = boneTransforms[mesh.ParentBone.Index];
                var meshCenter = Vector3.Transform(meshBounds.Center, transform);   
  
                float transformScale = transform.Forward.Length();   
  
                float meshRadius = (meshCenter - modelCenter).Length() +   
                                   (meshBounds.Radius * transformScale);   
  
                modelRadius = Math.Max(modelRadius, meshRadius);   
            }   
  
            return modelRadius;
        }
    }
}
